package com.ouman.luoliluoli;

import android.animation.Animator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ouman.luoliluoli.models.AppUpdateModel;
import com.ouman.luoliluoli.utils.DownloadAppUpdate;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.NetworkHelper;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class SplashActivity extends AppCompatActivity {


    private AppUpdateModel appUpdateModel;
    private String todayPictureUrl;
    private ImageView splashImageView;

    private ImageView imageViewLogo;

    private TextView textViewName;
    private TextView textViewWords;
    private View bkView;

    private String ads_image_url;
    private String ads_title;
    private String ads_content;
    private String ads_jump_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);
        splashImageView = (ImageView) findViewById(R.id.imageViewSplash);
        imageViewLogo = (ImageView) findViewById(R.id.imageViewLogo);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewWords = (TextView) findViewById(R.id.textViewWords);

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                | View.SYSTEM_UI_FLAG_IMMERSIVE);
//        getWindow().setNavigationBarColor(ResourcesCompat.getColor(getResources(), R.color.color14, null));


        splashImageView.post(new Runnable() {
            @Override
            public void run() {
                int cx = (splashImageView.getLeft() + splashImageView.getRight())/2;
                int cy = (splashImageView.getTop() + splashImageView.getBottom())/2;
                Animator animator= ViewAnimationUtils.createCircularReveal(splashImageView,cx,cy,200,600);
                animator.setInterpolator(new AccelerateInterpolator());
                animator.setDuration(1000);
                animator.start();
            }
        });

        AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
        alphaAnimation.setDuration(300);
        alphaAnimation.setStartOffset(600);
        textViewName.setAnimation(alphaAnimation);

        AlphaAnimation alphaAnimation2 = new AlphaAnimation(0.0f, 1.0f);
        alphaAnimation2.setDuration(600);
        alphaAnimation2.setStartOffset(600);
        textViewWords.setAnimation(alphaAnimation2);

        imageViewLogo.post(new Runnable() {
            @Override
            public void run() {
                int cx = (imageViewLogo.getLeft() + imageViewLogo.getRight())/2;
                int cy = (imageViewLogo.getTop() + imageViewLogo.getBottom())/2;
                Animator animator= ViewAnimationUtils.createCircularReveal(imageViewLogo,cx,cy,0,30);
                animator.setInterpolator(new AccelerateInterpolator());
                animator.setDuration(2000);
                animator.start();
            }
        });

        appUpdateModel = new AppUpdateModel();

        if (NetworkHelper.isConnect(SplashActivity.this)){
            new Thread(threadGetPicture).start();
            new Thread(threadCheckUpdate).start();
        } else{
            // 否则的话直接doJump，doJump是判断跳转到Login还是Main
            doJump();
        }


    }

    private  Thread threadGetPicture = new Thread(){
        public void run(){
            //In here we solve http request to get data
            HttpURLConnection connection = null;
            try {

                String urlAPI = GlobalConstants.API_SPLASH_ADS;
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    // !!!!!!!!以后最好加上这个，要不然会出现中文变成unicode问题，统一utf-8最好
                    String result = URLDecoder.decode(IOUtils.toString(is), "utf-8");
                    System.out.println(result);
                    is.close();

                    JSONObject jsonObject = new JSONObject(result);

                    String status = jsonObject.getString("status");
                    if(status.equals("success")){
                        JSONObject data = jsonObject.getJSONObject("data");
                        ads_image_url = GlobalConstants.API_BASE_URL + data.getString("ads_image_url");
                        ads_title = data.getString("ads_title");
                        ads_content = data.getString("ads_content");
                        ads_jump_url = data.getString("ads_image_jump_url");

                        Message msg = Message.obtain();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    } else{
                        System.out.println("no need to load splash image.");
                    }
                }
            } catch (JSONException e){
                e.printStackTrace();
            } catch (SocketTimeoutException e) {
                Message msg = Message.obtain();
                msg.what = 10;
                handler.sendMessage(msg);
            } catch (IOException e){
                e.printStackTrace();
            }
            finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };

    private  Thread threadCheckUpdate = new Thread(){
        public void run(){
            //In here we solve http request to get data
            HttpURLConnection connection = null;
            try {

                String urlAPI = GlobalConstants.API_APP_UPDATE;
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("POST");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();

                    JSONObject jsonObject = new JSONObject(result);
                    String status = jsonObject.getString("status");
                    if (status.equals("success")){
                        JSONObject jsonObjectChild = jsonObject.getJSONObject("data");
                        String app_update_version = jsonObjectChild.getString("app_update_version");
                        System.out.println("update version : " + app_update_version);
                        String app_update_intro = jsonObjectChild.getString("app_update_intro");
                        System.out.println("update intro : " + app_update_intro);
                        String app_update_detail = jsonObjectChild.getString("app_update_detail");
                        String app_update_url = jsonObjectChild.getString("app_update_url");
                        String app_update_size = jsonObjectChild.getString("app_update_size");
                        String release_time = jsonObjectChild.getString("release_time");


                        appUpdateModel.setApp_update_version(app_update_version);
                        appUpdateModel.setApp_update_intro(app_update_intro);
                        appUpdateModel.setApp_update_detail(app_update_detail);
                        appUpdateModel.setApp_update_url(app_update_url);
                        appUpdateModel.setApp_update_size(app_update_size);
                        appUpdateModel.setRelease_time(release_time);

                        Message msg = Message.obtain();
                        msg.what = 1;
                        // delay 3s to update UI
                        SystemClock.sleep(4500);
                        handler.sendMessage(msg);
                    } else {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    }

                }
            } catch (SocketTimeoutException e) {
                Message msg = Message.obtain();
                msg.what = 10;
                handler.sendMessage(msg);
            } catch (JSONException e){
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };


    private Thread threadUpdate = new Thread(){
        public void run(){
            DownloadAppUpdate.downloadForAutoInstall(SplashActivity.this,
                    appUpdateModel.getApp_update_url(), "luoliluoli", "test");
        }
    };
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                // status not success
                Toast.makeText(SplashActivity.this, "检查更新出现了错误, 但我们依旧可以继续", Toast.LENGTH_SHORT);
                doJump();

            }else if (msg.what == 1){
                // 判断一下是否更新
                String appNewVersion = appUpdateModel.getApp_update_version();
                if (shouldUpdate(appNewVersion)){
                    // do update code
                    // 即使需要更新也不要每次都弹出来，判断一天谈一次
                    if (dayOnceLaunch()){
                        AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
                        builder.setTitle("检测到更新");
                        builder.setMessage(appUpdateModel.getApp_update_intro() + "\n" + appUpdateModel.getApp_update_detail()
                                + "\n" + "更新包大小: " +appUpdateModel.getApp_update_size());
                        builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                doJump();
                            }
                        });
                        builder.setPositiveButton("后台更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                doJump();
                                // 后台更新代码
                                // 重新开一个线程更新
                                System.out.println("start update......!!!!!!!");
                                new Thread(threadUpdate).start();
                            }
                        });
                        builder.setCancelable(false);
                        builder.show();
                    } else{
                        doJump();
                    }

                } else{
                    doJump();
                }
            } else if (msg.what == 2){
                Glide.clear(splashImageView);
                Glide.with(SplashActivity.this)
                        .load(ads_image_url)
                        .asBitmap()
                        .error(R.drawable.bk_beauty)
                        .into(splashImageView);
                textViewName.setText(ads_title);
                textViewWords.setText(ads_content);
            } else if(msg.what == 10){
                Toast.makeText(SplashActivity.this, "连接服务器超时，直接跳转", Toast.LENGTH_SHORT).show();
                doJump();
            }
        }
    };

    public Boolean shouldUpdate(String versionNumber){
        // 判断是否需要更新
        PackageManager manager = SplashActivity.this.getPackageManager();
        String appVersionName = "default";
        Integer currentVersionCode = 1;
        try {
            PackageInfo info = manager.getPackageInfo(SplashActivity.this.getPackageName(), 0);
            appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("app version name: " + appVersionName + "app version code: " + currentVersionCode.toString());

        String localVersion = currentVersionCode.toString();

        if (localVersion.equals(versionNumber)){
            // version from server are same with local, no need to update
            return false;
        } else{
            // if not equal then should update
            return true;
        }

    }
    public void doJump(){
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SplashActivity.this);
        Boolean isLogin = preferences.getBoolean("isLogin", false);
        if (!isLogin){
            System.out.println("-----!!! 没有登陆Login Activity");
            Intent login = new Intent(SplashActivity.this, LoginActivity.class);
            SplashActivity.this.startActivity(login);
            finish();
        }else{
            // 直接跳转到main
            Intent main = new Intent(SplashActivity.this, MainActivity.class);
            SplashActivity.this.startActivity(main);
            finish();
        }
    }

    public Boolean dayOnceLaunch(){
        // 该方法判断是否满足一天执行一次的条件，如果满足返回true，不满足返回false，
        // 这里面执行的动作就是一天执行一次的动作
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SplashActivity.this);
        String lastDate = preferences.getString("lastDate", "2017121");

        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);
        Integer month = cal.get(Calendar.MONTH);
        Integer day = cal.get(Calendar.DAY_OF_MONTH);
        String todayDate = year.toString() + month.toString() + day.toString();

        System.out.println("Today date: " + todayDate);

        if (lastDate.equals(todayDate)){
            // indicates 这不是第一次启动，返回false
            return false;
        } else {
            // else返回真，并把todayDate存入
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("lastDate", todayDate);
            editor.apply();
            return true;
        }

    }

//    public void showSplash(){
//        System.out.println("fake display splash..");
//        // 如果没有网，那么就直接延时4s钟
//        new Thread(threadDelay).start();
//    }

}
